import { IMiddleware, Middleware } from '@midwayjs/core';
import { Context, NextFunction } from '@midwayjs/koa';
import { makeHttpRequest } from '@midwayjs/core';

@Middleware()
export class ProxyMiddleware implements IMiddleware<Context, NextFunction> {
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      await next(); // 先走本地路由
      console.log('ctx',ctx.status ,ctx.body)

      // 仅在本地未命中（404）时代理
      if (ctx.status === 404|| ctx.body == null) {
        const remoteUrl = 'http://apidev.szqerp.com' + ctx.path + (ctx.search || '');
        console.log('remoteUrl',remoteUrl)
        try {
          const result = await makeHttpRequest(remoteUrl, {
            method: ctx.method,
            data: ctx.request.body,
            headers: ctx.headers,
            dataType: 'json',
          });
          ctx.status = result.status;
          ctx.body = result.data;
        } catch (err) {
          ctx.status = 502;
          ctx.body = { success: false, message: '代理请求失败', error: err.message };
        }
      }
    };
  }

  static getName(): string {
    return 'proxy';
  }
}